package com.buric.common.strategy;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 策略工厂
 */

@Slf4j
@Component
public class StrategyFactory<T extends Strategy> extends ApplicationObjectSupport implements ApplicationListener<ContextRefreshedEvent> {

    /**
     * Enum<?>: 策略-枚举
     * Class<?>: 具体策略-Class
     */
    private final Map<String, Class<?>> classMap = new ConcurrentHashMap<>();

    private ApplicationContext context;


    @Override
    protected void initApplicationContext(ApplicationContext context) throws BeansException {
        super.initApplicationContext(context);
        this.context = context;
    }

    /**
     * 获取对应 策略实现
     *
     * @param code 策略-CODE
     * @return R ==> R extends BaseStrategy
     */
    public T getStrategy(String code) {
        return (T) this.context.getBean(classMap.get(code));
    }


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, Strategy> strategyMap = this.context.getBeansOfType(Strategy.class);
        strategyMap.forEach((key, value) -> {
            if (null == value.getKey()) {
                log.error("策略类: {}, 未配置策略KEY", key);
                throw new RuntimeException("未配置策略KEY");
            }
            classMap.put(value.getKey(), value.getClass());
        });
    }
}
